package com.shopping.controller;

import com.shopping.common.Result;
import com.shopping.entity.Order;
import com.shopping.entity.User;
import com.shopping.exception.BusinessException;
import com.shopping.service.OrderService;
import com.shopping.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @PostMapping
    public Result<Boolean> createOrder(@RequestBody Order order) {
        try {
            logger.info("创建订单请求: {}", order);

            // 验证必填字段
            if (order.getUserId() == null) {
                logger.error("创建订单失败: 用户ID不能为空");
                return Result.error("用户ID不能为空");
            }
            if (order.getProductId() == null) {
                logger.error("创建订单失败: 商品ID不能为空");
                return Result.error("商品ID不能为空");
            }
            if (order.getQuantity() == null || order.getQuantity() <= 0) {
                logger.error("创建订单失败: 商品数量必须大于0");
                return Result.error("商品数量必须大于0");
            }
            if (order.getAddress() == null || order.getAddress().trim().isEmpty()) {
                logger.error("创建订单失败: 收货地址不能为空");
                return Result.error("收货地址不能为空");
            }
            if (order.getContactPhone() == null || order.getContactPhone().trim().isEmpty()) {
                logger.error("创建订单失败: 联系方式不能为空");
                return Result.error("联系方式不能为空");
            }

            boolean success = orderService.createOrder(order);
            if (success) {
                logger.info("创建订单成功: orderId={}", order.getId());
                return Result.success(true);
            } else {
                logger.error("创建订单失败: 未知错误");
                return Result.error("创建订单失败");
            }
        } catch (BusinessException e) {
            logger.error("创建订单失败(业务异常): {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("创建订单失败(系统异常): ", e);
            return Result.error("创建订单失败，请稍后重试");
        }
    }

    @GetMapping("/user")
    public Result<List<Order>> getUserOrders() {
        try {
            // 从SecurityContext中获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                logger.warn("用户未登录");
                return Result.error("用户未登录");
            }

            // 获取用户名
            String username = authentication.getName();
            logger.info("获取用户订单, username: {}", username);

            // 根据用户名查询用户
            User user = userService.findByUsername(username);
            if (user == null) {
                logger.error("用户不存在: {}", username);
                return Result.error("用户不存在");
            }

            // 获取用户订单
            List<Order> orders = orderService.getUserOrders(user.getId());
            return Result.success(orders);
        } catch (Exception e) {
            logger.error("获取用户订单失败", e);
            return Result.error("获取订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/user/{userId}")
    public Result<List<Order>> getUserOrders(@PathVariable Long userId) {
        return Result.success(orderService.getUserOrders(userId));
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderDetail(@PathVariable Long id) {
        Order order = orderService.getOrderDetail(id);
        return order != null ? Result.success(order) : Result.error("订单不存在");
    }

    @PutMapping("/status")
    public Result<Boolean> updateOrderStatus(@RequestParam Long orderId, @RequestParam Order.OrderStatus status) {
        boolean success = orderService.updateOrderStatus(orderId, status);
        return success ? Result.success(true) : Result.error("更新订单状态失败");
    }

    @PutMapping("/{id}/confirm")
    public Result<Boolean> confirmOrder(@PathVariable Long id) {
        boolean success = orderService.updateOrderStatus(id, Order.OrderStatus.COMPLETED);
        return success ? Result.success(true) : Result.error("确认收货失败");
    }

    @PutMapping("/{id}/pay")
    public Result<Boolean> payOrder(@PathVariable Long id, @RequestBody Map<String, String> data) {
        boolean success = orderService.updateOrderStatus(id, Order.OrderStatus.PAID);
        return success ? Result.success(true) : Result.error("支付失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> cancelOrder(@PathVariable Long id) {
        boolean success = orderService.cancelOrder(id);
        return success ? Result.success(true) : Result.error("取消订单失败");
    }

    @GetMapping("/list")
    public Result<List<Order>> getAllOrders() {
        return Result.success(orderService.list());
    }
}